function transformMenuArray(menuArray) {
  const menuMap = {};

  // 初始化菜单映射表，使用 MenuId 作为键存储菜单项
  for (const menu of menuArray) {
    const { MenuId } = menu;
    menu.meta = menu.meta ? JSON.parse(menu.meta) : null; // 解析 JSON 格式的 meta 字符串为对象
    menuMap[MenuId] = menu;
  }

  const transformedMenu = [];

  // 将每个菜单项添加到其父菜单的 children 数组中
  for (const menu of menuArray) {
    const { FatherId } = menu;
    if (FatherId !== null && menuMap[FatherId]) {
      if (!menuMap[FatherId].children) {
        menuMap[FatherId].children = []; // 如果父菜单的 children 不存在，则初始化为一个空数组
      }
      menuMap[FatherId].children.push(menu);
    } else if (FatherId === null) {
      transformedMenu.push(menu); // 如果没有父菜单，将其作为顶级菜单添加到 transformedMenu 中
    }
  }

  // 返回转换后的菜单数组
  return transformedMenu;
}

function transformDepartmentArray(departmentArray) {
  const departmentMap = {};
  // 初始化部门映射表，使用 departmentId 作为键存储部门项
  for (const department of departmentArray) {
    const { departmentId } = department;
    departmentMap[departmentId] = department;
  }
  const transformedDepartment = [];
  for (const department of departmentArray) {
    const { fatherDepartmentId } = department;
    if (fatherDepartmentId !== null && departmentMap[fatherDepartmentId]) {
      if (!departmentMap[fatherDepartmentId].children) {
        departmentMap[fatherDepartmentId].children = [];
      }
      departmentMap[fatherDepartmentId].children.push(department);
    } else if (fatherDepartmentId === null) {
      transformedDepartment.push(department);
    }
  }
  return transformedDepartment;
}

module.exports = { transformMenuArray, transformDepartmentArray };
